package com.ideal.service.impl;

import com.ideal.config.Constant;
import com.ideal.dto.DictInfoDto;
import com.ideal.dto.FileConfigResultDto;
import com.ideal.dto.ResultDto;
import com.ideal.dto.config.res.FileResDto;
import com.ideal.model.ConfigVersion;
import com.ideal.service.IConfigVersionService;
import com.ideal.service.IFileService;
import com.ideal.service.ISysTreeDictService;
import com.ideal.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Objects;

/**
* @Author: lilei
* @Description: 文件业务实现
* @date: 2022/7/25
*/
@Service
public class IFileServiceImpl implements IFileService {

    @Autowired
    private ISysTreeDictService sysTreeDictService;

    @Autowired
    private IConfigVersionService configVersionService;

    @Override
    public ResultDto upload(MultipartFile file) {
        if (file.isEmpty()){
            return ResultDto.fail("上传文件为空");
        }       DictInfoDto dictInfoDto = sysTreeDictService.findOneByDictLabel(Constant.FILE_ACCESS_URL);
        if (Objects.isNull(dictInfoDto)){
            return ResultDto.fail("没有配置存储路径");
        }
        FileResDto fileResDto = new FileResDto();
        FileConfigResultDto upload = FileUtils.upload(dictInfoDto.getDictValue(), file);
        if (upload==null){
            return ResultDto.fail("文件上传失败，请重新上传");
        }
        fileResDto.setFileUrl(upload.getFilePath());
        return ResultDto.success(fileResDto);
    }

    @Override
    public String findFilePath(Long configVersionId) {
        final ConfigVersion configVersion = configVersionService.selectConfigVersionById(configVersionId);

        if (Objects.isNull(configVersion) || !StringUtils.hasLength(configVersion.getFileUrl())) {
            throw new RuntimeException("版本数据异常");
        }
        return configVersion.getFileUrl();
    }
}
